package org.budo.support.log4j.appender;

import java.io.Writer;

import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * appender
 * 
 * @author lmw
 */
public class BudoLog4jDailyRollingFileAppender extends AbstractBudoLog4jDailyRollingFileAppender {
    /**
     * The default maximum file size is 1GB.
     * 
     * @see org.apache.log4j.helpers.OptionConverter.toFileSize(String, long)
     */
    private long maxFileSize = 1024 * 1024 * 1024;

    private long nextRollover = 0;

    public void setFile(String file) {
        if (file.contains("#{") && file.contains("}")) {
            String fileWithExpression = BudoLog4jDailyRollingFileAppenderUtil.fileWithExpression(file);
            super.setFile(fileWithExpression);
        } else {
            super.setFile(file);
        }
    }

    protected void setQWForFiles(Writer writer) {
        this.qw = new CountingQuietWriter(writer, errorHandler);
    }

    protected void subAppend(LoggingEvent event) {
        super.subAppend(event);

        this.roll_over_by_size();
    }

    public void rollOver() {
        try {
            this.update_next_roll_over();

            super.rollOver();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    private void roll_over_by_size() {
        try {
            if (fileName != null && qw != null) {
                if (qw instanceof CountingQuietWriter) {
                    long size = ((CountingQuietWriter) qw).getCount();
                    if (size >= maxFileSize && size >= nextRollover) {
                        this.rollOver();
                    }
                }
            }
        } catch (Throwable e) {
            LogLog.error("roll_over_by_size 失败, e=" + e);
            e.printStackTrace();
        }
    }

    private void update_next_roll_over() {
        try {
            if (qw != null) {
                if (qw instanceof CountingQuietWriter) {
                    long size = ((CountingQuietWriter) qw).getCount();
                    LogLog.debug("rolling over count=" + size);
                    nextRollover = size + maxFileSize;
                }
            }
        } catch (Throwable e) {
            LogLog.error("update_next_roll_over 失败, e=" + e);
            e.printStackTrace();
        }
    }
}